package jmu.dao.impl;

import jmu.dao.MessageDAO;
import jmu.dao.RevertDAO;
import jmu.db.ConnectionManager;
import jmu.vo.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Repository
public class MessageDAOImpl implements MessageDAO {

    @Autowired
    private RevertDAO revertDAO;

    @Override
    public List<Message> findAllMessages() throws Exception {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Message> allMessages = new ArrayList<>();
        try {
            con = ConnectionManager.getConnection();
            String sql = "SELECT * FROM message";
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                Message message = new Message();
                message.setMessageID(rs.getInt("messageID"));
                message.setTitle(rs.getString("title"));
                message.setContent(rs.getString("content"));
                message.setWriter(rs.getString("writer"));
                message.setWriteDate(rs.getDate("writeDate"));
                allMessages.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeResultSet(rs);
            ConnectionManager.closeStatement(pstmt);
            ConnectionManager.closeConnection(con);
        }
        return allMessages;
    }

    @Override
    public Message findMessageById(int id) throws Exception {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            con = ConnectionManager.getConnection();
            String sql = "SELECT * FROM message WHERE messageID = ?";
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                Message message = new Message();
                message.setMessageID(rs.getInt("messageID"));
                message.setTitle(rs.getString("title"));
                message.setContent(rs.getString("content"));
                message.setWriter(rs.getString("writer"));
                message.setWriteDate(rs.getDate("writeDate"));
                return message;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeResultSet(rs);
            ConnectionManager.closeStatement(pstmt);
            ConnectionManager.closeConnection(con);
        }
        return null;
    }

    @Override
    public boolean insertMessages(Message message) throws Exception {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = ConnectionManager.getConnection();
            String sql = "INSERT INTO message (title, content, writer, writeDate) VALUES (?, ?, ?, ?)";
            pstmt = con.prepareStatement(sql);

            pstmt.setString(1, message.getTitle());
            pstmt.setString(2, message.getContent());
            pstmt.setString(3, message.getWriter());
            pstmt.setTimestamp(4, new Timestamp(System.currentTimeMillis()));

            int affectedRows = pstmt.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeStatement(pstmt);
            ConnectionManager.closeConnection(con);
        }
        return false;
    }

    @Override
    public boolean deleteMessages(int id) throws Exception {
        Connection con = null;
        PreparedStatement pstmt = null;
        boolean success = false;
        try {
            con = ConnectionManager.getConnection();

            con.setAutoCommit(false); // 开始事务

            // 1. 删除该留言下的所有回复
            boolean revertsDeleted = revertDAO.deleteRevertsByMessageID(con, id);
            if (!revertsDeleted) {
                throw new SQLException("Failed to delete reverts for message ID: " + id);
            }

            // 2. 删除留言
            String sql = "DELETE FROM message WHERE messageID = ?";
            pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, id);
            int affectedRows = pstmt.executeUpdate();
            success = affectedRows > 0;

            con.commit(); // 提交事务

        } catch (SQLException e) {
            if (con != null) {
                try {
                    con.rollback(); // 回滚事务
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            throw new RuntimeException("Transaction rolled back due to error", e);
        } finally {
            ConnectionManager.closeStatement(pstmt);
            ConnectionManager.closeConnection(con);
        }
        return success;
    }

    @Override
    public boolean updateMessages(Message message) throws Exception {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = ConnectionManager.getConnection();
            String sql = "UPDATE message SET title=?, content=?, writer=? WHERE messageID=?";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, message.getTitle());
            pstmt.setString(2, message.getContent());
            pstmt.setString(3, message.getWriter());
            pstmt.setInt(4, message.getMessageID());
            int affectedRows = pstmt.executeUpdate();
            return affectedRows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeStatement(pstmt);
            ConnectionManager.closeConnection(con);
        }
        return false;
    }

    @Override
    public List<Message> searchMessages(String keyword) throws Exception {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Message> messages = new ArrayList<>();
        try {
            con = ConnectionManager.getConnection();
            String sql = "SELECT * FROM message WHERE title LIKE ? OR content LIKE ?";
            pstmt = con.prepareStatement(sql);
            String searchPattern = "%" + keyword + "%";
            pstmt.setString(1, searchPattern);
            pstmt.setString(2, searchPattern);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                Message message = new Message();
                message.setMessageID(rs.getInt("messageID"));
                message.setTitle(rs.getString("title"));
                message.setContent(rs.getString("content"));
                message.setWriter(rs.getString("writer"));
                message.setWriteDate(rs.getDate("writeDate"));
                messages.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeResultSet(rs);
            ConnectionManager.closeStatement(pstmt);
            ConnectionManager.closeConnection(con);
        }
        return messages;
    }
}
